package jp.co.jbuy.action.product;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;

import jp.co.jbuy.action.BaseAction;
import jp.co.jbuy.external.api.yahoo.auction.product.YProductDetail;
import jp.co.jbuy.external.api.yahoo.auction.product.YProductGetException;
import jp.co.jbuy.product.ProductDetail;
import jp.co.jbuy.product.ProductDetailView;
import jp.co.jbuy.product.ProductImage;

public class ProductDetailAction extends BaseAction {
	public static final String PAGE_ID = "product_detail";
	public static final String PAGE_URL = "./jsp/product/productDetail.jsp";

	@Override
	public void action() throws Exception {
		int dataSource = this.getIntParameter("data_source");
		String auctionID = this.getRequest().getParameter("auction_id");

		ProductDetail productDetail = null;
		ProductDetailView productDetailView = null;
		List<String> errorList = new ArrayList<String>();

		try {
			if (dataSource == 1) {
				// Local DB.
				// productDetail = local.getDetail(auctionID);

			} else if (dataSource == 2) {
				// Yahoo API
				YProductDetail yp = new YProductDetail();
				productDetail = yp.getDetail(auctionID);

			} else if (dataSource == 3) {
				// Rakuten
			}

			if (productDetail != null) {
				List<ProductImage> imageList = productDetail.getImageList();
				if (imageList != null && imageList.size() > 0) {
					for (int i = 0; i < imageList.size(); i++) {
						if (i == 0)
							productDetail.setImage1(imageList.get(i));
						if (i == 1)
							productDetail.setImage2(imageList.get(i));
						if (i == 2)
							productDetail.setImage3(imageList.get(i));
					}
				}
				productDetailView = new ProductDetailView(productDetail);
			}
		} catch (FileNotFoundException e) {
			errorList.add("該当商品が見つかりません。");
		} catch (YProductGetException e) {
			errorList.add("商品情報取得失敗しました。");
		}

		req_.setAttribute("auctionID", auctionID);
		req_.setAttribute("pd", productDetail);
		req_.setAttribute("pdv", productDetailView);
		req_.setAttribute("reqURI", req_.getRequestURI());
		req_.setAttribute("errorList", errorList);
		forward(PAGE_URL);

	}

}
